/**
 * 导航跳转 Hook
 * 提供统一的页面跳转方法
 *
 * @example
 * ```typescript
 * import { useNavigation } from '@/hooks/useNavigation'
 *
 * const { navTo, backNav, redirectTo, reLaunchTo } = useNavigation()
 *
 * // 普通跳转
 * navTo('/pages/detail/index?id=123')
 *
 * // 返回上一页
 * backNav()
 *
 * // 关闭当前页跳转
 * redirectTo('/pages/home/index')  reT('/pages/home/index')
 *
 * // 关闭所有页面跳转
 * reLaunchTo('/pages/index/index')  reL('/pages/index/index')
 * ```
 */

interface NavigateOptions {
    /** 跳转路径 */
    url: string;
    /** 是否显示未开放提示，默认 true */
    showTips?: boolean;
    /** 提示文字，默认"暂未开放此功能" */
    tipsText?: string;
    /** 成功回调 */
    success?: () => void;
    /** 失败回调 */
    fail?: (error: any) => void;
    /** 完成回调 */
    complete?: () => void;
}

interface NavigationReturn {
    /** 普通跳转 */
    navTo: (url: string | NavigateOptions, vm?: any) => void;
    /** 返回上一页 */
    backNav: (delta?: number) => void;
    /** 关闭当前页跳转 */
    redirectTo: (url: string | NavigateOptions) => void;
    /** 关闭所有页面跳转 */
    reLaunchTo: (url: string | NavigateOptions) => void;
    /** 切换 Tab */
    switchTab: (url: string | NavigateOptions) => void;
    reT: (url: string | NavigateOptions) => void;
    reL: (url: string | NavigateOptions) => void;
}

export function useNavigation(): NavigationReturn {
    /**
     * 显示未开放提示
     */
    const showNotOpenTips = (text: string = "暂未开放此功能") => {
        uni.showToast({
            title: text,
            icon: "none",
            duration: 1000
        });
    };

    /**
     * 解析导航参数
     */
    const parseOptions = (urlOrOptions: string | NavigateOptions): NavigateOptions => {
        if (typeof urlOrOptions === "string") {
            return {
                url: urlOrOptions,
                showTips: true,
                tipsText: "暂未开放此功能"
            };
        }
        return {
            showTips: true,
            tipsText: "暂未开放此功能",
            ...urlOrOptions
        };
    };

    /**
     * 普通跳转（保留当前页面）
     * @param urlOrOptions 跳转路径或配置对象
     * @param vm 页面实例（可选）
     */
    const navTo = (urlOrOptions: string | NavigateOptions, vm?: any): void => {
        const options = parseOptions(urlOrOptions);

        // 如果没有 URL，显示提示
        if (!options.url) {
            if (options.showTips) {
                showNotOpenTips(options.tipsText);
            }
            return;
        }

        // 保存页面实例到 uni 对象
        if (vm) {
            uni.$vm = vm;
        }

        console.log("[useNavigation] navTo:", options.url);

        uni.navigateTo({
            url: options.url,
            success: () => {
                console.log("[useNavigation] navTo success");
                options.success?.();
            },
            fail: error => {
                console.error("[useNavigation] navTo fail:", error);
                options.fail?.(error);
            },
            complete: () => {
                options.complete?.();
            }
        });
    };

    /**
     * 返回上一页
     * @param delta 返回的页面数，默认 1
     */
    const backNav = (delta: number = 1): void => {
        const pages = getCurrentPages();

        console.log("[useNavigation] backNav, pages length:", pages.length);

        // 如果只有一个页面，跳转到首页
        if (pages.length === 1) {
            console.log("[useNavigation] 只有一个页面，跳转到首页");
            uni.redirectTo({
                url: "/pages/index/index",
                fail: error => {
                    console.error("[useNavigation] redirectTo fail:", error);
                }
            });
        } else {
            uni.navigateBack({
                delta,
                fail: error => {
                    console.error("[useNavigation] navigateBack fail:", error);
                }
            });
        }
    };

    /**
     * 关闭当前页面跳转
     * @param urlOrOptions 跳转路径或配置对象
     */
    const redirectTo = (urlOrOptions: string | NavigateOptions): void => {
        const options = parseOptions(urlOrOptions);

        if (!options.url) {
            if (options.showTips) {
                showNotOpenTips(options.tipsText);
            }
            return;
        }

        console.log("[useNavigation] redirectTo:", options.url);

        uni.redirectTo({
            url: options.url,
            success: () => {
                console.log("[useNavigation] redirectTo success");
                options.success?.();
            },
            fail: error => {
                console.error("[useNavigation] redirectTo fail:", error);
                options.fail?.(error);
            },
            complete: () => {
                options.complete?.();
            }
        });
    };

    /**
     * 关闭所有页面跳转
     * @param urlOrOptions 跳转路径或配置对象
     */
    const reLaunchTo = (urlOrOptions: string | NavigateOptions): void => {
        const options = parseOptions(urlOrOptions);

        if (!options.url) {
            if (options.showTips) {
                showNotOpenTips(options.tipsText);
            }
            return;
        }

        console.log("[useNavigation] reLaunchTo:", options.url);

        uni.reLaunch({
            url: options.url,
            success: () => {
                console.log("[useNavigation] reLaunchTo success");
                options.success?.();
            },
            fail: error => {
                console.error("[useNavigation] reLaunchTo fail:", error);
                options.fail?.(error);
            },
            complete: () => {
                options.complete?.();
            }
        });
    };

    /**
     * 切换 Tab 页面
     * @param urlOrOptions 跳转路径或配置对象
     */
    const switchTab = (urlOrOptions: string | NavigateOptions): void => {
        const options = parseOptions(urlOrOptions);

        if (!options.url) {
            if (options.showTips) {
                showNotOpenTips(options.tipsText);
            }
            return;
        }

        console.log("[useNavigation] switchTab:", options.url);

        uni.switchTab({
            url: options.url,
            success: () => {
                console.log("[useNavigation] switchTab success");
                options.success?.();
            },
            fail: error => {
                console.error("[useNavigation] switchTab fail:", error);
                options.fail?.(error);
            },
            complete: () => {
                options.complete?.();
            }
        });
    };

    return {
        navTo,
        backNav,
        redirectTo,
        reLaunchTo,
        switchTab,
        reT: redirectTo, // 简写别名
        reL: reLaunchTo // 简写别名
    };
}

// 默认导出
export default useNavigation;
